package defines

import (
	"encoding/json"
	"net/http"
)

// Return JSON响应结构体
type Return struct {
	Error   int         `json:"error"`
	Message string      `json:"message"`
	Data    interface{} `json:"data"`
}

// ToJsonByte 将Return结构体转换为JSON字节数组
func (r *Return) ToJsonByte() []byte {
	str, err := json.MarshalIndent(r, "", "\t")
	if err != nil {
		return []byte{}
	}
	return str
}

// ResponseJson 将Return结构体以JSON格式写入HTTP响应
func (r *Return) ResponseJson(w http.ResponseWriter) error {
	w.Header().Set("Content-Type", "application/json; charset=utf-8")
	str, err := json.MarshalIndent(r, "", "\t")
	if err != nil {
		return err
	}

	_, err2 := w.Write(str)
	return err2
}
